// 文字识别
var appkeyMen = function() {
	return new Promise((resolve, reject) => {
		let url = 'https://aip.baidubce.com/oauth/2.0/token'
		let data = {
			grant_type: "client_credentials", //必须参数，固定为client_credentials； 
			client_id: "BAZwUvnMCcv0fgigGcEdSHuG", //必须参数，应用的API Key；
			client_secret: "6cBcyiBDPPQnG7QToZQWeVrxebvcePXa" //必须参数，应用的Secret Key；
		}
		uni.request({
			url: url,
			method: 'POST',
			header: {
				'content-Type': 'application/x-www-form-urlencoded',
			},
			data: data,
			success: (res) => {
				console.log('[文字识别参数sus]', res)
				let access_token = res.data.access_token
				resolve(access_token)
			},
			fail(err) {
				reject(err)
				console.log('[文字识别参数err]', err)
			}
		})
	})
}

var recognition = function() {

	return new Promise((resolve, reject) => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			success: (res) => {
				// uni.showLoading({
				// 	'title': "文字识别中"
				// })
				
				
				
				resolve(res.tempFilePaths[0])
				return
				let url = res.tempFilePaths[0]
				// #ifdef MP-WEIXIN
				uni.getFileSystemManager().readFile({
					filePath: url, //选择图片返回的相对路径
					encoding: 'base64', //编码格式
					success: res => { //成功的回调
						console.log(res);
						let base64 = 'data:image/jpeg;base64,' + res
							.data //不加上这串字符，在页面无法显示的哦
						let data = {
							base64: res.data,
							imgUrl: base64,
							url: url
						}
						resolve(data)
					},
					fail: (e) => {
						console.log("图片转换失败");
						reject(e)
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				uni.request({
					url: url,
					method: 'GET',
					responseType: 'arraybuffer',
					success: ress => {
						let base641 = wx.arrayBufferToBase64(ress
							.data); //把arraybuffer转成base64 
						let base64 = 'data:image/jpeg;base64,' +
							base641 //不加上这串字符，在页面无法显示的哦
						let data = {
							base64: base641,
							imgUrl: base64,
							url: url,
						}
						console.log('[成功]', data);
						resolve(data)
					},
					fail: (e) => {
						uni.showModal({
							title:'图片转换失败',
							content:'嗯'
						})
						console.log("图片转换失败");
						reject(e)
					}
				})
				// #endif
			}
		})

	})
}


var sweep = function(rems) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic',
			method: 'POST',
			header: {
				'content-Type': 'application/x-www-form-urlencoded',
			},
			data: {
				access_token: rems.access_token,
				image: rems.base64,
				language_type: 'CHN_ENG'
			},
			success: (res) => {
				const us = res.data.words_result
				resolve(res)
				uni.hideLoading()
			},
			fail(err) {
				console.log('[失败]', err)
				uni.hideLoading()
			},
			complete() {
				uni.hideLoading()
			}
		})

	})
}




export {
	recognition,
	appkeyMen,
	sweep
}
